﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UtilZ.Dotnet.Ex.Base;
using UtilZ.Dotnet.Ex.ZLog;

namespace UtilZ.Dotnet.Ex.Communication.Net.Ftp
{
    /// <summary>
    /// 为特性选择选项
    /// RFC 2389	Select options for a feature.
    /// </summary>
    internal class FtpOPTSCommand : FtpCommandAbs
    {
        /***********************************************************************************************************
        *
        *
        ************************************************************************************************************/


        public FtpOPTSCommand()
            : base()
        {

        }

        protected override string[] GetNames()
        {
            return new string[] { FtpCommands.OPTS };
        }

        protected override IFtpResponse PrimitiveExcute(FtpSession session, string command, string commandLine)
        {
            //Request: opts utf8 on
            //Response: 200 OPTS UTF8 command successful - UTF8 encoding now ON.

            try
            {
                if (string.IsNullOrEmpty(commandLine))
                {
                    return new FtpCodeResponse(FtpStatusCodes.Code500, "command require encoding name.");
                }

                string[] strs = commandLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                if (strs.Length >= 2 && !string.Equals(strs[1], "on", StringComparison.OrdinalIgnoreCase))
                {
                    //修改为默认编码
                    session.Encoding = session.FtpServer.Config.Encoding;
                }
                else
                {
                    //修改为指定的编码
                    session.Encoding = EncodingEx.GetEncoding(strs[0]);
                }

                ZLoger.Debug($"修改字符集编码为:{session.Encoding.EncodingName}");
                //return new FtpTextResponse("230 ok");
                return new FtpCodeResponse(FtpStatusCodes.Code200, $"OPTS {strs[0].ToUpper()} command successful. {strs[0]} encoding now on.");
            }
            catch (Exception ex)
            {
                return new FtpCodeResponse(FtpStatusCodes.Code504, ex.Message);
            }
        }
    }

}
